<template>
  <div>
    {{ totalData }}
    <p-table
      class="table-list-container"
      :row-key="(record, index) => index"
      :pagination="false"
      :columns="columns"
      bordered
      :data-source="totalData"
    />
  </div>
</template>

<script>
import { isObject } from '@/utils/is';
import _ from 'lodash';
import Decimal from 'decimal.js';
let idKey = 0;

export default {
  props: {
    dataSource: {
      type: Array,
      default: () => [
        {
          customerName: '华为',
          application: '手机',
          monthSupplyDemands: [
            {
              month: '2021-09',
              supplyDemand: {
                demand: 10,
                supply: 12,
                difference: 11,
              },
            },
            {
              month: '2021-10',
              supplyDemand: {
                demand: 101,
                difference: 111,
                supply: 112,
              },
            },
          ],
        },
        {
          application: '平板',
          customerName: '华为',
          monthSupplyDemands: [
            {
              month: '2021-09',
              supplyDemand: {
                demand: 10,
                difference: 11,
                supply: 12,
              },
            },
            {
              month: '2021-10',
              supplyDemand: {
                demand: 101,
                difference: 111,
                supply: 112,
              },
            },
          ],
        },
        {
          application: '手机',
          customerName: '小米',
          monthSupplyDemands: [
            {
              month: '2021-09',
              supplyDemand: {
                demand: 10,
                difference: 11,
                supply: 12,
              },
            },
            {
              month: '2021-10',
              supplyDemand: {
                demand: 101123,
                difference: 111,
                supply: 112,
              },
            },
          ],
        },
        {
          application: '平板',
          customerName: '小米',
          monthSupplyDemands: [
            {
              month: '2021-09',
              supplyDemand: {
                demand: 10,
                difference: 11,
                supply: 12,
              },
            },
            {
              month: '2021-10',
              supplyDemand: {
                demand: 101123,
                difference: 111,
                supply: 112,
              },
            },
          ],
        },
      ],
    },
  },
  data() {
    return {};
  },
  computed: {
    totalKeys() {
      const defaultObj = this.formatList[0] || {};
      const obj = Object.keys(defaultObj)
        .filter((key) => isObject(defaultObj[key]))
        .reduce((pre, cur) => {
          pre[`${cur}.demand`] = '';
          pre[`${cur}.supply`] = '';
          pre[`${cur}.difference`] = '';
          return pre;
        }, {});

      return Object.keys(obj);
    },
    formatList() {
      if (!this.dataSource.length) return [];
      return this.dataSource.map((item) => {
        const months = item.monthSupplyDemands?.reduce((pre, cur) => {
          pre[cur.month] = cur.supplyDemand;
          return pre;
        }, {});
        return {
          id: ++idKey,
          application: item.application,
          ...months,
        };
      });
    },
    groups() {
      return this.formatList.reduce((pre, cur) => {
        if (pre[cur.customerName]) {
          pre[cur.customerName].push(cur);
        } else {
          pre[cur.customerName] = [cur];
        }
        return pre;
      }, {});
    },
    totalData() {
      const groupTotal = Object.keys(this.groups).map((group) => {
        const total = this.groups[group].reduce(
          (pre, cur) => {
            this.totalKeys.forEach((key) => {
              if (!_.get(pre, key)) {
                _.set(pre, key, 0);
              }
              const tempValue = new Decimal(_.get(pre, key)).plus(
                new Decimal(_.get(cur, key) || 0)
              );
              if (key.startsWith('price')) {
                _.set(pre, key, tempValue.toFixed(2));
              } else {
                _.set(pre, key, tempValue.toFixed());
              }
            });
            return pre;
          },
          { id: 'totalKey', application: '小计' }
        );
        return [...this.groups[group], total];
      });

      const totalAll = this.formatList.reduce(
        (pre, cur) => {
          this.totalKeys.forEach((key) => {
            if (!_.get(pre, key)) {
              _.set(pre, key, 0);
            }
            const tempValue = new Decimal(_.get(pre, key)).plus(
              new Decimal(_.get(cur, key) || 0)
            );
            if (key.startsWith('price')) {
              _.set(pre, key, tempValue.toFixed(2));
            } else {
              _.set(pre, key, tempValue.toFixed());
            }
          });
          return pre;
        },
        { id: 'totalKeyAll', customerName: '总计' }
      );

      return [...this.formatList, { ...totalAll, application: '总计' }];
    },
    columns() {
      if (!this.formatList.length) return [];
      const titleObj = {
        application: '应用别',
        demand: '需求',
        supply: '供应',
        difference: '供需差异',
      };

      const defaultObj = this.formatList[0] || {};
      const columns = Object.keys(defaultObj)
        .filter((key) => isObject(defaultObj[key]))
        .map((item) => {
          const value = defaultObj[item];
          const column = {
            align: 'center',
            title: item,
            children: Object.keys(value).map((el) => {
              return {
                align: 'center',
                title: titleObj[el],
                dataIndex: `${item}.${el}`,
              };
            }),
          };
          return column;
        });
      const defaultColumns = ['customerName', 'application'].map((item) => {
        const title = titleObj[item];
        return {
          align: 'center',
          title,
          dataIndex: item,
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, item);
          },
        };
      });
      return [...defaultColumns, ...columns];
    },
  },

  methods: {
    delOne(str, arr) {
      const index = arr.indexOf(str);
      arr.splice(index, 1);
      return arr;
    },
    customRender(children, index, row, key) {
      const attrs = {};
      if (key === 'customerName') {
        const data = this.groups[row.customerName] || [];
        console.log('data: ', data);
        if (row.id === data[0]?.id) {
          attrs.rowSpan = data.length + 1;
        } else if (row.id === 'totalKeyAll') {
          attrs.rowSpan = 1;
          attrs.colSpan = 2;
        } else {
          attrs.rowSpan = 0;
        }
      }
      if (key === 'application' && row.id === 'totalKeyAll') {
        attrs.colSpan = 0;
      }
      return {
        children,
        attrs,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.table-list-container {
  margin-top: 20px;
}
</style>
